function [ subjectinfo ] = analyzeVisualResponsiveness_PrepareSets( subjectinfo )
%ANALYZEVISUALRESPONSIVENESS_PREPARESETS

subjectinfo.Analyses.VisualResponsiveness = [];

% STEP 1 Epoch the data 
subjectinfo = prepareFilepath(subjectinfo); % Prepare the filepath structure
subjectinfo = Step1(subjectinfo);

subjectinfo.Save();

end




%% Preparation
function [ s ] = prepareFilepath( s )
    s.Analyses.VisualResponsiveness.Filepath = [s.FilepathBase 'Visual Responsiveness\'];
    if ~exist(s.Analyses.VisualResponsiveness.Filepath, 'dir')
        mkdir(s.FilepathBase, 'Visual Responsiveness');
    end
end

%% Step 1
function [s] = Step1(s)
VisualResponsiveness = s.Analyses.VisualResponsiveness;
%% Epoch/Segment the data
VisualResponsiveness.Sets = [];
DATA = [];
for d=1:length(s.Datasets)
    %% Load the preprocessed data
    EEG = pop_loadset('filename', s.Datasets(d).PreprocessedFilename);
    
    
    %% Treat different types of sets accordingly
    switch s.Datasets(d).Type
        case {'Sphere Intermittend'}
            % Create 3 separate sets to analyze:
            %   A - Continuous on/off + Intermittend on/off
            %   B - Continuous on/off + Intermittend off
            %   C - Continuous on/off
            
            setNumber = length(VisualResponsiveness.Sets)+1;
            % Describe the set
            description = [s.Name ' - Set ' num2str(d) 'A - Continuous on/off + Intermittend on/off'];
            VisualResponsiveness.Sets(setNumber).Description = description;
            VisualResponsiveness.Sets(setNumber).Identifier = [s.PrimaryPrefix num2str(d)];
            VisualResponsiveness.Sets(setNumber).Type = 'SphIntA';            
            DATA(end+1).Type = [s.Datasets(d).Type 'A'];
            [on off] = findStimulusOnOff(EEG.event, 'intermittendOnEnabled', 1, 'intermittendOffEnabled', 1);
            REST = pop_select(EEG, 'time', off/EEG.srate);
            REST = eeg_checkset(REST);
            % Save the epochs to a new file
            VisualResponsiveness.Sets(setNumber).DataFilenameRest = ...
                [VisualResponsiveness.Filepath s.PrimaryPrefix num2str(d) 'A Rest Epochs.set'];
            DATA(end).REST = pop_saveset(REST, 'filename', VisualResponsiveness.Sets(setNumber).DataFilenameRest);
            STIM = pop_select(EEG, 'time', on/EEG.srate);
            STIM = eeg_checkset(STIM);
            % Save the epochs to a new file
            VisualResponsiveness.Sets(setNumber).DataFilenameStimulus = ...
                [VisualResponsiveness.Filepath s.PrimaryPrefix num2str(d) 'A Stimulus Epochs.set'];
            DATA(end).STIM = pop_saveset(STIM, 'filename', VisualResponsiveness.Sets(setNumber).DataFilenameStimulus);
            
            setNumber = setNumber + 1;
            % Describe the set
            description = [s.Name ' - Set ' num2str(d) 'B - Continuous on/off + Intermittend off'];
            VisualResponsiveness.Sets(setNumber).Description = description;
            VisualResponsiveness.Sets(setNumber).Identifier = [s.PrimaryPrefix num2str(d)];
            VisualResponsiveness.Sets(setNumber).Type = 'SphIntB';
            DATA(end+1).Type = [s.Datasets(d).Type 'B'];
            [on off] = findStimulusOnOff(EEG.event, 'intermittendOnEnabled', 0, 'intermittendOffEnabled', 1);
            REST = pop_select(EEG, 'time', off/EEG.srate);
            REST = eeg_checkset(REST);
            % Save the epochs to a new file
            VisualResponsiveness.Sets(setNumber).DataFilenameRest = ...
                [VisualResponsiveness.Filepath s.PrimaryPrefix num2str(d) 'B Rest Epochs.set'];
            DATA(end).REST = pop_saveset(REST, 'filename', VisualResponsiveness.Sets(setNumber).DataFilenameRest);
            STIM = pop_select(EEG, 'time', on/EEG.srate);
            STIM = eeg_checkset(STIM);
            % Save the epochs to a new file
            VisualResponsiveness.Sets(setNumber).DataFilenameStimulus = ...
                [VisualResponsiveness.Filepath s.PrimaryPrefix num2str(d) 'B Stimulus Epochs.set'];
            DATA(end).STIM = pop_saveset(STIM, 'filename', VisualResponsiveness.Sets(setNumber).DataFilenameStimulus);
            
            setNumber = setNumber + 1;
            % Describe the set
            description = [s.Name ' - Set ' num2str(d) 'C - Continuous on/off'];
            VisualResponsiveness.Sets(setNumber).Description = description;
            VisualResponsiveness.Sets(setNumber).Identifier = [s.PrimaryPrefix num2str(d)];
            VisualResponsiveness.Sets(setNumber).Type = 'SphIntC';
            DATA(end+1).Type = [s.Datasets(d).Type 'C'];
            [on off] = findStimulusOnOff(EEG.event, 'intermittendOnEnabled', 0, 'intermittendOffEnabled', 0);
            REST = pop_select(EEG, 'time', off/EEG.srate);
            REST = eeg_checkset(REST);
            % Save the epochs to a new file
            VisualResponsiveness.Sets(setNumber).DataFilenameRest = ...
                [VisualResponsiveness.Filepath s.PrimaryPrefix num2str(d) 'C Rest Epochs.set'];
            DATA(end).REST = pop_saveset(REST, 'filename', VisualResponsiveness.Sets(setNumber).DataFilenameRest);
            STIM = pop_select(EEG, 'time', on/EEG.srate);
            STIM = eeg_checkset(STIM);
            % Save the epochs to a new file
            VisualResponsiveness.Sets(setNumber).DataFilenameStimulus = ...
                [VisualResponsiveness.Filepath s.PrimaryPrefix num2str(d) 'C Stimulus Epochs.set'];
            DATA(end).STIM = pop_saveset(STIM, 'filename', VisualResponsiveness.Sets(setNumber).DataFilenameStimulus);
            
        case {'FaceHouse'}
            DATA(end+1).Type = s.Datasets(d).Type;
            setNumber = length(VisualResponsiveness.Sets)+1;
            
            % Describe the set
            description = [s.Name ' - Set ' num2str(d) ' - ' s.Datasets(d).Type];
            VisualResponsiveness.Sets(setNumber).Description = description;
            VisualResponsiveness.Sets(setNumber).Identifier = [s.PrimaryPrefix num2str(d)];
            VisualResponsiveness.Sets(setNumber).Type = 'FaceHouse';
            
            % Extract Rest epochs
            newsetname = [s.Name ' - Set ' num2str(d) ' - Rest epochs'];
            REST = pop_epoch(EEG, {'S-Rest-10'}, [0 10], 'newname', newsetname, 'epochinfo', 'yes');
            REST = pop_rmbase( REST, [0 10000]); % Remove base to minimize gain interference
            REST = eeg_checkset(REST);
            % Save the epochs to a new file
            VisualResponsiveness.Sets(setNumber).DataFilenameRest = ...
                [VisualResponsiveness.Filepath s.PrimaryPrefix num2str(d) ' Rest Epochs.set'];
            DATA(end).REST = pop_saveset(REST, 'filename', VisualResponsiveness.Sets(setNumber).DataFilenameRest);
            
            % Extract All Stimulus epochs
            
            startBlockMarkers = [];
            stimulusMarkers = strmatch('S-', {EEG.event(:).type}); % Only keep the stimulus markers
            for i = 1:length(stimulusMarkers)
                if strcmp(EEG.event(stimulusMarkers(i)).type, 'S-FH-A')
                    startBlockMarkers = [startBlockMarkers,stimulusMarkers(i)];
                elseif i>1 && strcmp(EEG.event(stimulusMarkers(i-1)).type, 'S-Rest-10') % WERKT NIET ALS ER EEN R TUSSEN STAAT
                    startBlockMarkers = [startBlockMarkers,stimulusMarkers(i)];
                elseif i == 1 && (strcmp(EEG.event(stimulusMarkers(i)).type, 'S-FH-F') || strcmp(EEG.event(stimulusMarkers(i)).type, 'S-FH-H'))
                    startBlockMarkers = [startBlockMarkers,stimulusMarkers(i)];
                end
            end            
            newsetname = [s.Name ' - Set ' num2str(d) ' - Stimulus epochs'];
            STIM = pop_epoch(EEG, [], [0 120], 'newname', newsetname, 'epochinfo', 'yes', 'eventindices', startBlockMarkers);
            %TODO: Figure this out!! EEG = pop_rmbase( EEG, [0  0]);
            STIM = pop_rmbase( STIM, [0 120000]);
            STIM = eeg_checkset(STIM);
            % Save the epochs to a new file
            VisualResponsiveness.Sets(setNumber).DataFilenameStimulus = ...
                [VisualResponsiveness.Filepath s.PrimaryPrefix num2str(d) ' Stimulus Epochs.set'];
            DATA(end).STIM = pop_saveset(STIM, 'filename', VisualResponsiveness.Sets(setNumber).DataFilenameStimulus);
            
        case {'Sphere'}
            DATA(end+1).Type = s.Datasets(d).Type;
            setNumber = length(VisualResponsiveness.Sets)+1;
            
            % Describe the set
            description = [s.Name ' - Set ' num2str(d) ' - ' s.Datasets(d).Type];
            VisualResponsiveness.Sets(setNumber).Description = description;
            VisualResponsiveness.Sets(setNumber).Identifier = [s.PrimaryPrefix num2str(d)];
            VisualResponsiveness.Sets(setNumber).Type = 'Sphere';
            
            % Extract Rest epochs
            newsetname = [s.Name ' - Set ' num2str(d) ' - Rest epochs'];
            REST = pop_epoch(EEG, {'S-Rest-10'}, [0 10], 'newname', newsetname, 'epochinfo', 'yes');
            REST = pop_rmbase( REST, [0 10000]); % Remove base to minimize gain interference
            REST = eeg_checkset(REST);
            % Save the epochs to a new file
            VisualResponsiveness.Sets(setNumber).DataFilenameRest = ...
                [VisualResponsiveness.Filepath s.PrimaryPrefix num2str(d) ' Rest Epochs.set'];
            DATA(end).REST = pop_saveset(REST, 'filename', VisualResponsiveness.Sets(setNumber).DataFilenameRest);
            
            % Extract All Stimulus epochs
            newsetname = [s.Name ' - Set ' num2str(d) ' - Stimulus epochs'];
            STIM = pop_epoch(EEG, {'S-SC-A' 'S-SC-U'}, [0 120], 'newname', newsetname, 'epochinfo', 'yes');
            %TODO: Figure this out!! EEG = pop_rmbase( EEG, [0  0]);
            STIM = pop_rmbase( STIM, [0 120000]);
            STIM = eeg_checkset(STIM);
            % Save the epochs to a new file
            VisualResponsiveness.Sets(setNumber).DataFilenameStimulus = ...
                [VisualResponsiveness.Filepath s.PrimaryPrefix num2str(d) ' Stimulus Epochs.set'];
            DATA(end).STIM = pop_saveset(STIM, 'filename', VisualResponsiveness.Sets(setNumber).DataFilenameStimulus);
            
        case {'SphereVoluntary'}
            DATA(end+1).Type = s.Datasets(d).Type;
            setNumber = length(VisualResponsiveness.Sets)+1;
            
            % Describe the set
            description = [s.Name ' - Set ' num2str(d) ' - ' s.Datasets(d).Type];
            VisualResponsiveness.Sets(setNumber).Description = description;
            VisualResponsiveness.Sets(setNumber).Identifier = [s.PrimaryPrefix num2str(d)];
            VisualResponsiveness.Sets(setNumber).Type = 'SphVol';
            
            % Extract Rest epochs
            newsetname = [s.Name ' - Set ' num2str(d) ' - Rest epochs'];
            REST = pop_epoch(EEG, {'S-Rest-10'}, [0 10], 'newname', newsetname, 'epochinfo', 'yes');
            REST = pop_rmbase( REST, [0 10000]); % Remove base to minimize gain interference
            REST = eeg_checkset(REST);
            % Save the epochs to a new file
            VisualResponsiveness.Sets(setNumber).DataFilenameRest = ...
                [VisualResponsiveness.Filepath s.PrimaryPrefix num2str(d) ' Rest Epochs.set'];
            DATA(end).REST = pop_saveset(REST, 'filename', VisualResponsiveness.Sets(setNumber).DataFilenameRest);
            
            % Extract All Stimulus epochs
            newsetname = [s.Name ' - Set ' num2str(d) ' - Stimulus epochs'];
            STIM = pop_epoch(EEG, {'S-SV-A'}, [0 120], 'newname', newsetname, 'epochinfo', 'yes');
            %TODO: Figure this out!! EEG = pop_rmbase( EEG, [0  0]);
            STIM = pop_rmbase( STIM, [0 120000]);
            STIM = eeg_checkset(STIM);
            % Save the epochs to a new file
            VisualResponsiveness.Sets(setNumber).DataFilenameStimulus = ...
                [VisualResponsiveness.Filepath s.PrimaryPrefix num2str(d) ' Stimulus Epochs.set'];
            DATA(end).STIM = pop_saveset(STIM, 'filename', VisualResponsiveness.Sets(setNumber).DataFilenameStimulus);
            
        otherwise
            error('Scenario unknown.')
            
    end
end

%% Add averages incase more than one trial of same type
trialTypes = unique({s.Datasets(:).Type}); % Get the distinct typenames for this subject
MERGE = [];
    for t = 1:length(trialTypes) % Loop through to merge all sets of same type
        count = 0;
        MergedREST = [];
        MergedSTIM = [];
        for d = 1:length(DATA)
            if strcmp(DATA(d).Type, trialTypes(t))
                if count == 0 % Don't merge the first set..
                    MergedREST = DATA(d).REST;
                    MergedSTIM = DATA(d).STIM;
                else
                    MergedREST = pop_mergeset( MergedREST, DATA(d).REST, 0 );
                    MergedSTIM = pop_mergeset( MergedSTIM, DATA(d).STIM, 0 );
                end
                count = count + 1;
            end
        end
        if count > 1 % Only save when there is more than one set in the merged data (otherwise it has already been saved as a regular set)
            % Determine the set number
            setNumber = length(VisualResponsiveness.Sets)+1;
            % Describe the set
            description = [s.Name ' - All sets of ' cell2mat(trialTypes(t))];
            VisualResponsiveness.Sets(setNumber).Description = description;
            VisualResponsiveness.Sets(setNumber).Identifier = [s.PrimaryPrefix 'X'];
            VisualResponsiveness.Sets(setNumber).Type = ['All ' cell2mat(trialTypes(t))];
            MergedREST = pop_editset(MergedREST, 'setname', [description ' - Rest epochs']);
            MergedSTIM = pop_editset(MergedSTIM, 'setname', [description ' - Stimulus epochs']);
            % Save the merged sets
            VisualResponsiveness.Sets(setNumber).DataFilenameRest = ...
                [VisualResponsiveness.Filepath s.PrimaryPrefix ' All sets of ' cell2mat(trialTypes(t)) ' Rest Epochs.set'];
            MERGE(t).REST = pop_saveset(MergedREST, 'filename', VisualResponsiveness.Sets(setNumber).DataFilenameRest);
            VisualResponsiveness.Sets(setNumber).DataFilenameStimulus = ...
                [VisualResponsiveness.Filepath s.PrimaryPrefix ' All sets of ' cell2mat(trialTypes(t)) ' Stimulus Epochs.set'];
            MERGE(t).STIM = pop_saveset(MergedSTIM, 'filename', VisualResponsiveness.Sets(setNumber).DataFilenameStimulus);
        else % Keep the set for the total merge later, but don't save to disk
            MERGE(t).REST = MergedREST;
            MERGE(t).STIM = MergedSTIM;
        end
    end

%% Add average over all trials
if length(MERGE) > 1
    for t = 1:length(MERGE) % Loop again to merge everything
        MergedREST = [];
        MergedSTIM = [];
        if isempty(MergedREST) % && isempty(AvgSTIM)
            MergedREST = MERGE(t).REST;
            MergedSTIM = MERGE(t).STIM;
        else
            MergedREST = pop_mergeset( MergedREST, MERGE(t).REST, 0 );
            MergedSTIM = pop_mergeset( MergedSTIM, MERGE(t).STIM, 0 );
        end
    end
    if ~isempty(MergedREST) % && isempty(AvgSTIM)
        % Determine the set number
        setNumber = length(VisualResponsiveness.Sets)+1;
        % Describe the set
        description = [s.Name ' - All sets'];
        VisualResponsiveness.Sets(setNumber).Description = description;
        VisualResponsiveness.Sets(setNumber).Identifier = [s.PrimaryPrefix  'X'];
        VisualResponsiveness.Sets(setNumber).Type = 'All';
        MergedREST = pop_editset(MergedREST, 'setname', [description ' - Rest epochs']);
        MergedSTIM = pop_editset(MergedSTIM, 'setname', [description ' - Stimulus epochs']);
        % Save the merged sets
        VisualResponsiveness.Sets(setNumber).DataFilenameRest = ...
            [VisualResponsiveness.Filepath s.PrimaryPrefix ' All Rest Epochs.set'];
        pop_saveset(MergedREST, 'filename', VisualResponsiveness.Sets(setNumber).DataFilenameRest);
        VisualResponsiveness.Sets(setNumber).DataFilenameStimulus = ...
            [VisualResponsiveness.Filepath s.PrimaryPrefix ' All Stimulus Epochs.set'];
        pop_saveset(MergedSTIM, 'filename', VisualResponsiveness.Sets(setNumber).DataFilenameStimulus);
    end
end

%% Augment the subject information
s.Analyses.VisualResponsiveness = VisualResponsiveness;
end

